/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------


var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析

var ajax = require("mlib/io/ajax");
var when = require("mlib/util/when");
var wx = require("mlib/util/jweixin");
var closest = require("mlib/dom/closest");
var touch = require("mlib/evt/touch");
//var isTouch = require("mlib/evt/isTouch");
var jsonp = require("mlib/io/jsonp");
var mix = require("mlib/util/mix");
var virtualLink = require("mlib/util/virtualLink");
var lottery = require("./lottery"); 
var showMessage = require("../layer/info");
window.wechat = wx;

module.exports = function(node, opts) {
	
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
	var doc_h = null;
	
	
    var wxOpts = {
			trigger: function (res) {},
			success: function (res) {},
			cancel: function (res) {},
			fail: function (res) {},
			complete:function(res){}		
	};
	
    //-------------事件响应声明---------------
    var evtFuncs = {
         viewRegular:function(e){
         	 //_czc.push(["_trackEvent", "活动", "规则", "点击规则"]);
			 if(nodeList.viewrules.classList.contains("collapse")){
				 nodeList.viewrules.classList.remove("collapse");
				 nodeList.viewrules.style.height = doc_h +"px";
				 nodeList.viewrules.classList.add("expand");
			 }else{
				 nodeList.viewrules.classList.remove("expand");
				 nodeList.viewrules.style.height = "0px";
				 nodeList.viewrules.classList.add("collapse");
			 }
			 
		 },
		 myLottery:function(){
			if(that.isLock()) {
				return;
			}
			that.lock();
			ajax({
				url: data.url.myPrizeApi,
				onSuccess: function(res) { 
					that.unLock();
					if(res.error==0){
						if(res.data.length>0){
							location.href =  nodeList.mylottery.getAttribute("data-link");
						}else{
							showMessage("还没有奖品哦，快去抽奖吧~");
						}
					}                       
				},
				onError: function(xmlHttp) { 
					that.unLock();
					showMessage("程序错误");
				}
			});
		},
		hideGuide:function(){
			nodeList.sharetip.style.display = 'none';
			//isTouch(false);
		},
		shareGuide:function(){
			nodeList.sharetip.style.display = 'block';
           // isTouch(true);
		}
    }

    //-------------子模块实例化---------------
    var initMod = function() {
    	//pc端页面fontsize
    	var style = document.createElement("style");
    	var header = document.getElementsByTagName("head")[0];
    	var rootHtml = document.getElementsByTagName("html")[0];
    	var isAndroid = /android/gi.test(navigator.appVersion);
		var isIPhone = /iphone/gi.test(navigator.appVersion);
    	if(!isAndroid && !isIPhone){
//  		rootHtml.style.fontSize = "15px!important";
			style.innerHTML = "html { font-size: 15px!important; }";
			header.appendChild(style);
    	}
		doc_h = document.documentElement.clientHeight;
		nodeList.sharetip.style.height = doc_h +"px";
		
         lottery(".turntable").init(data);
         
         virtualLink(function(evt){
			 var target = closest(evt.target,".receive-btn",true);
			 if(target){
				 //_czc.push(["_trackEvent", "活动", "抽奖", "点击领取奖品"]);	
			 }
             location.href = evt.target.getAttribute("data-href");
         });
		
		custFuncs.getShareData().then(function(result) {
			// 微信分享	
			custFuncs.initWechat(result.data);
		});

    }

    //-------------绑定事件------------------
    var bindEvents = function() {       
	    touch.on(nodeList.mylottery,"tap",evtFuncs.myLottery);
	    touch.on(nodeList.regular,"tap",evtFuncs.viewRegular);
		touch.on(nodeList.sharelottery,"tap",evtFuncs.shareGuide);
		touch.on(nodeList.sharetip,"tap",evtFuncs.hideGuide);
    }

    //-------------自定义函数----------------
    var custFuncs = {
			initWechat:function(shareApiData){
				
				var wxConfig = {
					debug: true,
					appId: shareApiData.appid,
					timestamp: parseInt(shareApiData.jstimestamp),
					nonceStr: shareApiData.jsnoncestr,
					signature: shareApiData.signature,
					jsApiList: [
						'checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','showMenuItems'
					]
				}
				wx.config(wxConfig);

			   wx.ready(function () {
				//要分享的数据
				var shareData = data.shareData;
				//shareData
					// data.shareData
					wx.hideOptionMenu({
						"menuList":[
							'menuItem:openWithQQBrowser',//用QQ浏览器打开
							'menuItem:openWithSafari',//用Safari打开
							'menuItem:copyUrl',//复制链接
							'menuItem:share:QZone',//分享到QQ空间
							'menuItem:share:qq'//分享到QQ
						]
					});
					wx.showMenuItems({
						"menuList": [
							'menuItem:share:timeline',//分享朋友圈
							'menuItem:share:appMessage',//发送给朋友
							'menuItem:refresh',//刷新
							'menuItem:profile',//查看公众号（已添加）
							'menuItem:addContact',//查看公众号（未添加）
							'menuItem:profile',//查看公众号（已添加）
							'menuItem:dayMode',//日间模式
							'menuItem:nightMode'//夜间模式
						],
					});
				//分享给好友	type(1：朋友圈；2：好友)
				var shareAppMessage = {
				"title": shareData.title,
				"desc": shareData.desc,
				"link": shareData.link,
				"imgUrl": shareData.imgUrl,
				"dataUrl": shareData.dataUrl,
				success: function success() {
					ajax({
						url: data.url.shareApi,
						data:{"type":2},
						onSuccess: function onSuccess(res) {},
						onError: function onError(xmlHttp) {
							that.unLock();
								//showMessage("程序错误");
							}
						});
					}
				};
				//分享到朋友圈 type(1：朋友圈；2：好友)
				var shareTimeline = {
					"title": shareData.title + ',' + shareData.desc,
					"link": shareData.link,
					"imgUrl": shareData.imgUrl,
					success: function success() {
						ajax({
							url: data.url.shareApi,
							data:{"type":1},
							onSuccess: function onSuccess(res) {
								
							},
							onError: function onError(xmlHttp) {
								that.unLock();
								//showMessage("程序错误");
							}
						});
					}
				};

					//分享给好友
					wx.onMenuShareAppMessage(shareAppMessage);

					//分享到朋友圈
					wx.onMenuShareTimeline(shareTimeline);
				});
				
			},
			getShareData:function(){
				var defer = when.defer();
				jsonp(data.wxSign + '&url='+encodeURIComponent(location.href), {}, function(err, result){
					defer.resolve(result);
				});
				return defer.promise;
			}
	
    }

    //-------------一切从这开始--------------
    var init = function(_data) {
        data = _data;
        // 根据数据初始化模块
        // opts["render"]({ "title": data["title"] });

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();
    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};